<template>
  <div
    v-loading="loading"
    element-loading-text="文件上传中..."
    style="border: 1px solid #ccc"
    class="flex flex-col h-full w-full"
  >
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      class="flex-1"
      style="height: 100%; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChange"
      @onDestroyed="handleDestroyed"
      @onFocus="handleFocus"
      @onBlur="handleBlur"
      @customPaste="handlePaste"
      @customAlert="handleAlert"
      @onMaxLength="handleMaxLength"
    />
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  onBeforeUnmount,
  shallowRef,
  onMounted,
  reactive,
  toRefs,
  watch,
} from "vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IEditorConfig, IToolbarConfig, IDomEditor } from "@wangeditor/editor";
import { ElMessage } from "element-plus";
import { _getFileupload } from "@/api/const/index";

export default defineComponent({
  components: { Editor, Toolbar },
  emits: ["update:modelValue"],
  props: {
    modelValue: {
      type: String,
      default: "",
    },
    // 编辑器提示信息
    placeholder: {
      type: String,
      default: "",
    },
    // 模式（// 'default'经典模式 或 'simple'精简模式）
    mode: {
      type: String,
      default: "default",
    },
    maxLength: {
      type: Number,
      default: 0,
    },
  },
  setup(props, { emit }) {
    // 编辑器实例，必须用 shallowRef
    const editorRef = shallowRef();
    const editorConfig = {
      placeholder: props.placeholder,
      maxLength: props.maxLength,
      // 配置图片上传接口
      MENU_CONF: {
        ["uploadImage"]: {
          async customUpload(file: any, insertFn: any) {
            const formData = new FormData();
            formData.append("file", file);
            formData.append("purpose", "4");
            edit.loading = true;
            _getFileupload(formData)
              .then((res: any) => {
                if (res.code == 10000) {
                  insertFn(res.data.filePath);
                  ElMessage.success(res.message);
                  edit.loading = false;
                } else {
                  ElMessage.warning(res.message);
                  edit.loading = false;
                }
              })
              .catch((err: any) => {
                console.log(err);
              });
          },
        },
      } as any,
    } as Partial<IEditorConfig>; //编辑器配置
    const edit = reactive({
      valueHtml: props.modelValue, //内容 HTML
      loading: false,
      // 编辑器创建完毕时的回调函数。
      handleCreated: (editor: IDomEditor) => {
        editorRef.value = editor; // 记录 editor 实例，重要！
      },
      handleMaxLength: () => {
        ElMessage.warning(`当前字数已达到最大限制字数${props.maxLength}`);
      },
      // 编辑器内容、选区变化时的回调函数。
      handleChange: (editor: IDomEditor) => {
        emit("update:modelValue", edit.valueHtml);
      },
      // 编辑器销毁时的回调函数。调用 editor.destroy() 即可销毁编辑器
      handleDestroyed: (editor: IDomEditor) => {
        // console.log("content2", editor);
      },
      // 编辑器 focus 时的回调函数。
      handleFocus: (editor: IDomEditor) => {
        // console.log("content3", editor);
      },
      // 编辑器 blur 时的回调函数。
      handleBlur: (editor: IDomEditor) => {
        // console.log("content4", editor);
      },
      // 自定义粘贴。可阻止编辑器的默认粘贴，实现自己的粘贴逻辑。
      handlePaste: (editor: IDomEditor, event: ClipboardEvent) => {},
      // 自定义编辑器 alert
      handleAlert: (s: string, t: string) => {
        // switch (t) {
        //   case 'success':
        //       ElMessage.success(s)
        //       break
        //   case 'info':
        //       ElMessage.info(s)
        //       break
        //   case 'warning':
        //       ElMessage.warning(s)
        //       break
        //   case 'error':
        //       ElMessage.error(s)
        //       break
        //   default:
        //       ElMessage.info(s)
        //       break
        // }
      },
    });
    const toolbars = reactive({
      toolbarConfig: {
        excludeKeys: ["group-video", "insertImage"],
      } as Partial<IToolbarConfig>, //工具栏配置
    });

    watch(
      () => props.modelValue,
      (n, o) => {
        edit.valueHtml = n;
      }
    );
    onMounted(() => {});
    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
      const editor = editorRef.value;
      if (editor == null) return;
      editor.destroy();
    });
    return {
      ...toRefs(edit),
      ...toRefs(toolbars),
      editorRef,
      editorConfig,
    };
  },
});
</script>

<style scoped></style>
